<?php

/*
*/

class Order_model extends CI_Model
{

	static $table;
	private $error;

	public function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
		//载入库文件
		$this->load->library('form_validation');
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
		//初始化
		$this->table = 'orders';
		$this->error = '';
	}

	public function create($pur_app_id=0)
	{
		$data = array();
		$data['order_number'] = date("YmdHis", time()) . substr(time(), -6);
		$data['order_user_id'] = $this->input->cookie('user_id');
		$data['order_realname'] = $this->input->cookie('realname');
		$data['create_date'] = time();
		//计算总共进货应付价格
		$single_prices = $this->input->post('single_prices');
		$quantities = $this->input->post('quantities');
		if (count($single_prices) == count($quantities))
		{
			$data['order_total_price'] = 0;
			foreach ($single_prices as $k => $sp)
			{
				if ($single_prices[$k] > 0 && $quantities[$k] > 0)
				{
					$data['order_total_price'] += $sp * $quantities[$k];
				}
				else
				{
					$this->error = __FUNCTION__ . ':UNKOWN ERROR ON LINE ' . __LINE__;
					return false;
				}
			}
			if (0 != $pur_app_id)
			{
				$data['pur_app_id'] = $pur_app_id;
			}
			$this->db->insert($this->table, $data);
			return $this->db->insert_id();
			//var_dump($data);
		}
		else
		{
			$this->error = __FUNCTION__ . ':UNKOWN ERROR ON LINE ' . __LINE__;
		}
	}

	public function get_one($order_id)
	{
		$this->db->where('order_id', $order_id);
		$query = $this->db->get($this->table);
		if ($query->num_rows() == 1)
		{
			foreach ($query->result() as $data)
			{
				return get_object_vars($data);
			}
		}
		else
		{
			$this->error = '不存在的订单';
		}
	}

	public function get_total()
	{
		$query = $this->db->get($this->table);
		return $query->num_rows();
	}

	public function get_list($start, $limit, $order_by='dateline')
	{
		if ('dateline' == $order_by)
		{
			$this->db->order_by('create_date', 'DESC');
		}
		$query = $this->db->get($this->table, $limit, $start);
		return $query->result();
	}

}